/**
 * Created by ryansecreat on 2017/12/29.
 */

const { APIClientBase }=require("cluster-client");
class ClusterClient extends APIClientBase {
    get DataClient() {
        return require('./client');
    }

    get delegates() {
        return {
            unPublish: 'invokeOneway',
        };
    }

    get clusterOptions() {
        return {
            responseTimeout: 1000,
            port:8088,
        };
    }

    subscribe(...args) {
        return this._client.subscribe(...args);
    }

    unSubscribe(...args) {
        return this._client.unSubscribe(...args);
    }

    publish(...args) {
        return this._client.publish(...args);
    }

    unPublish(...args) {
        return this._client.unPublish(...args);
    }

    close() {
        return this._client.close();
    }
}

let foo=async ()=>{
    try {
        const client_1 = new ClusterClient();
        const client_2 = new ClusterClient();

        const listener_1 = val => {
            //console.log("foo_received_2",val);
            client_1.emit( 'foo_received_1', val );
        };
        const listener_2 = val => {
           // console.log("foo_received_2",val);
            client_2.emit( 'foo_received_2', val );
        };

// subscribe
        client_1.subscribe( {key: 'foo'}, val => {
            client_1.emit( 'foo_received', val );
        } );
        client_1.subscribe( {key: 'foo'}, listener_1 );


        client_2.subscribe({ key: 'foo' }, val => {
            client_2.emit('foo_received', val);
        });
        client_2.subscribe({ key: 'foo' }, listener_2);

        let ret = await client_2.await( 'foo_received' );
        console.log("foo_received",ret );

        client_2.publish({ key: 'foo', value: 'bar1' });

        let result= await Promise.all([client_1.await("foo_received"),client_2.await("foo_received")])
        console.log("foo_received",result);

        client_2.unPublish({ key: 'foo',value:"bar1"});

        result= await Promise.all([client_1.await("foo_received"),client_2.await("foo_received")])
        console.log("foo_received",result);

        client_1.close();
        client_2.close();


    }
    catch(e)
    {
        console.error(e);
    }

};

foo();



